package com.ice.base.util;

import java.util.concurrent.*;

/**
 * @Description 线程池工具类
 */
public class ThreadPoolUtil {

    //核心线程数，会一直存活，即使没有任务，线程池也会维护线程的最少数量
    private static final int SIZE_CORE_POOL = 8;
    //线程池维护线程的最大数量
    private static final int SIZE_MAX_POOL = 16;
    // 线程池维护线程所允许的空闲时间
    private static final long ALIVE_TIME = 60;
    //线程缓冲队列
    private static LinkedBlockingQueue queue = new LinkedBlockingQueue(32);

    private static ThreadPoolExecutor threadPool;

    public static void execute(Runnable runnable){
        getThreadPool().execute(runnable);
    }

    public static <T> Future<T> submit(Callable<T> callable){
        return getThreadPool().submit(callable);
    }


    public static ThreadPoolExecutor getThreadPool() {
        if(null != threadPool)
            return threadPool;

        synchronized (ThreadPoolUtil.class){
            if(null == threadPool)
                threadPool = new ThreadPoolExecutor(SIZE_CORE_POOL, SIZE_MAX_POOL, ALIVE_TIME, TimeUnit.SECONDS, queue,
                        new ThreadPoolExecutor.CallerRunsPolicy());
            return threadPool;
        }
    }
}
